package com.wlz.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlz.demo.common.ResultUtil;
import com.wlz.demo.entity.Files;
import com.wlz.demo.mapper.FileMapper;
import com.wlz.demo.service.IFilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 文件上传相关接口
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Resource
    private FileMapper fileMapper;

    @Autowired(required = true)
    private IFilesService iFilesService;

    /**
     * 文件上传接口
     * @param file 前端传递过来的文件
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException{

        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();

        //
        File uploadParentFile = new File(fileUploadPath);
        if (!uploadParentFile.exists()){
            uploadParentFile.mkdir();
        }

        // 定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid+"."+type;
        File uploadFile = new File(fileUploadPath+uuid+"."+type);

        //存到磁盘
        file.transferTo(uploadFile);


        //存到数据库
        String url = "http://124.221.133.96:9090/file/"+fileUUID;
        Files saveFile = new Files();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size/1024);
        saveFile.setUrl(url);
        fileMapper.insert(saveFile);

        return url;
    }

    /**
     * 文件下载接口   http://localhost:9090/file/{fileUUID}
     * @param fileUUID
     * @param response
     * @throws IOException
     */
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUUID);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }




    @DeleteMapping("/{id}")
    public ResultUtil<?> delete(@PathVariable Integer id) {
        Files files = fileMapper.selectById(id);
        files.setIsDelete(true);
        fileMapper.updateById(files);
        return ResultUtil.success(200,"删除成功");
    }

    /**
     * 分页查询接口
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    //cache缓存
//    @Cacheable(key = "#page+'-'+#pageSize"
//    @Cacheable(value = "files",key = "#pageNum+'-'+#pageSize+'-'+#name")
    public IPage<Files> findPage(@RequestParam Integer pageNum,
                                 @RequestParam Integer pageSize,
                                 @RequestParam(required=false) String name) {
        LambdaQueryWrapper<Files> lqw = new LambdaQueryWrapper<>();

        lqw.like(name!=null,Files::getName,name);

        //逻辑删除 getIsDelete == false 代表 文件没有逻辑删除 返回给页面
        // 当 getIsDelete == true 文件有逻辑删除 不返回给页面

        lqw.eq(Files::getIsDelete,false);

        IPage<Files> iPage = new Page<>(pageNum,pageSize);

        IPage<Files> page = iFilesService.page(iPage,lqw);

        return page;

    }

}
